<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="来访人姓名" prop="visitorName" label-width="85px">
        <el-input
          v-model="queryParams.visitorName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 修改：来访时间范围选择器 -->
      <el-form-item label="来访时间" prop="visitTimeRange">
        <el-date-picker
          clearable
          v-model="queryParams.visitTimeRange"
          type="daterange"
          range-separator="-"
          start-placeholder="请选择开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          placeholder="请选择时间范围"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 预约类型筛选按钮 -->
    <div class="status-buttons">
      <div
        class="status-btn"
        :class="{ active: selectedType === '' }"
        @click="handleClick('')"
      >
        全部
      </div>
      <div
        class="status-btn"
        :class="{ active: selectedType === '参观预约' }"
        @click="handleClick('参观预约')"
      >
        参观预约
      </div>
      <div
        class="status-btn"
        :class="{ active: selectedType === '探访预约' }"
        @click="handleClick('探访预约')"
      >
        探访预约
      </div>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['system:elderly:add']"
          >来访登记</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="laifangList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="来访类型" align="center" prop="visitorType" />
      <el-table-column label="来访人姓名" align="center" prop="visitorName" />
      <el-table-column label="来访人手机号" align="center" prop="phone" />
      <el-table-column label="老人姓名" align="center" width="150">
        <template #default="scope">
          {{ scope.row.elderlyName || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="来访时间"
        align="center"
        prop="visitTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.visitTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="150">
        <template #default="scope">
          {{ scope.row.creatorName || "-" }}
        </template>
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="额外字段1" align="center" prop="extraField1" />
      <el-table-column label="额外字段2" align="center" prop="extraField2" /> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['commanage:laifang:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['commanage:laifang:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来访登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="laifangRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="来访类型" prop="visitorType" style="margin-left: 13px;">
          <el-radio-group v-model="form.visitorType" @change="handleVisitorTypeChange">
            <el-radio label="参观预约">参观预约</el-radio>
            <el-radio label="探访预约">探访预约</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="来访人姓名" prop="visitorName" label-width="95px">
          <div class="input-with-count">
            <el-input
              v-model="form.visitorName"
              placeholder="请输入"
              :maxlength="maxLength.visitorName"
            />
            <span class="char-count">{{ visitorNameCount }}</span>
          </div>
        </el-form-item>

        <el-form-item label="手机号" prop="phone" style="margin-left: 13px;">
          <div class="input-with-count">
            <el-input
              v-model="form.phone"
              placeholder="请输入"
              :maxlength="maxLength.phone"
            />
            <span class="char-count">{{ phoneCount }}</span>
          </div>
        </el-form-item>

        <!-- 根据来访类型动态显示老人姓名输入方式 -->
        <el-form-item 
          v-if="form.visitorType === '参观预约'" 
          label="老人姓名" 
          prop="elderlyName" 
          style="margin-left: 13px;"
          :required="false"
        >
          <div class="input-with-count">
            <el-input
              v-model="form.elderlyName"
              placeholder="请输入"
              :maxlength="maxLength.elderlyName"
            />
            <span class="char-count">{{ elderlyNameCount }}</span>
          </div>
        </el-form-item>

        <el-form-item 
          v-if="form.visitorType === '探访预约'" 
          label="老人姓名" 
          prop="elderlyId" 
          style="margin-left: 13px;"
          :required="true" 
        >
          <el-select v-model="form.elderlyId" placeholder="请选择老人">
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="`${elderly.id} - ${elderly.name}`"
              :value="elderly.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="来访时间" prop="visitTime" style="margin-left: 13px;">
          <el-date-picker
            clearable
            v-model="form.visitTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择来访时间"
            :disabled-date="disabledPastDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Laifang">
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
console.log("姓名为" + userStore.nickName);

import {
  listLaifang,
  getLaifang,
  delLaifang,
  addLaifang,
  updateLaifang,
} from "@/api/commanage/laifang";
import { listElderly } from "@/api/system/elderly"; // 注意路径与实际接口文件一致
import { ref, reactive, toRefs, compile } from "vue";
const elderlyList = ref([]); // 老人列表数据（存储id和elderlyName）

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");

const laifangList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedType = ref(""); // 预约类型筛选（文本匹配）

const maxLength = reactive({
  visitorName: 10,
  phone: 11,
  elderlyName: 10,
});
/** 禁用今天之前的日期 */
const disabledPastDate = (date) => {
  // 获取今天的凌晨时间（毫秒级）
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  // 日期在今天之前（返回true则禁用），今天及之后（返回false则可用）
  return date < today;
};

// 监听来访类型变化，重置相关字段
const handleVisitorTypeChange = (value) => {
  if (value === '参观预约') {
    form.value.elderlyId = null;
  } else {
    form.value.elderlyName = null;
  }
}



// 新增：获取老人列表的函数
function loadElderlyList() {
  // 调用接口（若后端需要分页，可传{ pageNum: 1, pageSize: 100 }获取全部）
  listElderly()
    .then((response) => {
      // 假设后端返回格式为 { rows: [...老人数据数组...] }
      elderlyList.value = response.rows;
      // 若后端直接返回数组，则用 elderlyList.value = response;
    })
    .catch((error) => {
      console.error("获取老人列表失败：", error);
    });
}

// 组件初始化时调用，加载老人列表
loadElderlyList();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    visitorType: null,
    visitorName: null,
    phone: null,
    // 修改：将单个时间改为时间范围数组
    visitTimeRange: null, // 格式：[开始时间, 结束时间]
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
    visitorType: [
      { required: true, message: "来访类型不能为空", trigger: "blur" },
    ],
    visitorName: [
      { required: true, message: "来访人姓名不能为空", trigger: "blur" },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z\s]{1,10}$/,
        message: "姓名仅支持汉字、字母和空格，长度1-10",
        trigger: "blur",
      },
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的11位手机号",
        trigger: "blur",
      },
    ],
    elderlyName: [
      { required: true, message: "老人姓名不能为空", trigger: "blur" },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z\s]{1,10}$/,
        message: "姓名仅支持汉字、字母和空格，长度1-10",
        trigger: "blur",
      },
    ],
    visitTime: [
      { required: true, message: "来访时间不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// ---------- 新增：计算已输入字符数 ----------
const visitorNameCount = computed(() => {
  return `${form.value.visitorName?.length || 0}/${maxLength.visitorName}`;
});
const phoneCount = computed(() => {
  return `${form.value.phone?.length || 0}/${maxLength.phone}`;
});
const elderlyNameCount = computed(() => {
  return `${form.value.elderlyName?.length || 0}/${maxLength.elderlyName}`;
});

/** 查询来访登记列表（适配时间范围筛选） */
function getList() {
  // 复制参数并处理时间范围
  const params = { ...queryParams.value };

  // 将时间范围拆分为开始时间和结束时间（后端通常需要这两个参数）
  if (params.visitTimeRange && params.visitTimeRange.length === 2) {
    params.visitTimeStart = params.visitTimeRange[0]; // 开始时间
    params.visitTimeEnd = params.visitTimeRange[1]; // 结束时间
  }

  // 删除原数组参数，避免后端接收异常
  delete params.visitTimeRange;

  console.log("查询参数：", params);

  loading.value = true;
  listLaifang(params).then((response) => {
    laifangList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    visitorType: '参观预约',
    elderlyName: null, // 新增：老人姓名输入框字段
    visitorName: null,
    phone: null,
    elderlyId: null,
    visitTime: null,
    creator: userStore.id,
    createTime: null,
    status: null,
    extraField1: null,
    extraField2: null,
    elderlyName: null,
  };
  proxy.resetForm("laifangRef");
}

/** 类型筛选按钮点击事件 */
const handleClick = (value) => {
  console.log(value);

  selectedType.value = value;
  queryParams.value.visitorType = value || null;
  queryParams.value.pageNum = 1;
  getList();
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作（同步重置时间范围） */
function resetQuery() {
  proxy.resetForm("queryRef");
  selectedType.value = "";
  queryParams.value.visitorType = null;
  // 新增：重置时间范围
  queryParams.value.visitTimeRange = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "来访登记";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLaifang(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改来访登记";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["laifangRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLaifang(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLaifang(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除来访登记编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delLaifang(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  // 处理导出参数（同查询逻辑）
  const params = { ...queryParams.value };
  if (params.visitTimeRange && params.visitTimeRange.length === 2) {
    params.visitTimeStart = params.visitTimeRange[0];
    params.visitTimeEnd = params.visitTimeRange[1];
  }
  delete params.visitTimeRange;

  proxy.download(
    "commanage/laifang/export",
    params,
    `laifang_${new Date().getTime()}.xlsx`
  );
}

/** 时间格式化函数（修复表格渲染） */
function parseTime(time, format = "{y}-{m}-{d} {h}:{i}:{s}") {
  if (!time) return "";
  const date = new Date(time);
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    return value.toString().padStart(2, "0");
  });
}

getList();
</script>
<style scoped>
/* 原有样式保持不变 */
.status-buttons {
  display: flex;
  gap: 12px;
  padding: 8px 16px;
  background-color: #f2f2f2;
  margin: 10px 0;
  width: fit-content;
  border-radius: 4px;
  flex-wrap: wrap;
}

.status-btn {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #303133;
  transition: all 0.2s;
}

.status-btn.active {
  background: #fff;
  color: #1890ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.status-btn:not(.active):hover {
  background: #e5e7eb;
}

.el-dialog .el-form {
  margin-top: 16px;
}

.el-dialog .dialog-footer {
  margin-top: 24px;
}

.el-table .el-tag {
  padding: 4px 8px;
  font-size: 12px;
}

.small-padding .el-button {
  padding: 0 6px;
}
.char-count {
  color: #909399; /* 灰色，与示例风格匹配 */
  font-size: 12px;
}
.input-with-count {
  position: relative;
  width: 100%;
}

.input-with-count .el-input {
  padding-right: 60px; /* 给右侧计数预留空间 */
}

.input-with-count .char-count {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  margin-left: 0; /* 清除原有margin */
  pointer-events: none; /* 避免点击计数文本影响输入 */
}
</style>
